package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021/7/19.<br><br>
 *
 * 密钥格式化
 */
public class Topic482 {

    public static void main(String[] args) {
        Topic482 instance = new Topic482();

        System.out.println(instance.licenseKeyFormatting("5F3Z-2e-9-w", 4));
        System.out.println(instance.licenseKeyFormatting("2-5g-3-J", 2));
        System.out.println(instance.licenseKeyFormatting("--a-a-a--", 1));
    }

    public String licenseKeyFormatting(String s, int k) {
        StringBuilder builder = new StringBuilder();

        int counter = k;
        char[] array = s.toCharArray();
        for(int i = array.length - 1; i >= 0; i--) {
            if(array[i] == '-') {
                continue;
            }

            if(array[i] >= 'a') {
                builder.append((char) (array[i] - 32));
            }
            else {
                builder.append(array[i]);
            }
            counter--;

            if(counter == 0 && i > 0) {
                builder.append('-');
                counter = k;
            }
        }

        if(builder.length() > 0 && builder.charAt(builder.length() - 1) == '-') {
            builder.setLength(builder.length() - 1);
        }

        return builder.reverse().toString();
    }
}
